package retry;

import com.github.rholder.retry.*;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * 重试机制
 *
 * @author miweidong
 * @date 2021-08-27 15:07
 * @description 记一次guava重试机制
 * question: 希望在重试过程中可以被外界打断,而停止后续重试
 * url: https://blog.csdn.net/songhaifengshuaige/article/details/79440285
 */
public class TestRetry {
    private static int i = 1;

    public static void main(String[] args) {
        Retryer<String> retryer = RetryerBuilder.<String>newBuilder()
                .retryIfException()
                .retryIfResult(TestRetry::request)
                .withStopStrategy(StopStrategies.stopAfterAttempt(5))
                .withWaitStrategy(WaitStrategies.fixedWait(1L, TimeUnit.SECONDS))
                .build();
        try {
            retryer.call(() -> {
                try {
                    return retry();
                } catch (Exception e) {
                    throw new Exception(e);
                }
            });
        } catch (RetryException e) {
            System.out.println(e);
            e.printStackTrace();
        } catch (ExecutionException e) {
            System.out.println(e);
            e.printStackTrace();
        }
    }

    public static String retry() {
        System.out.println("重试触发:" + i);
//        if (i == 3) {
//            return "good";
//        }
        i++;
        return "good";
    }

    public static boolean request(String str) {
        return !"god".equals(str);
    }
}
